package com.foreknow.elmboot.service.impl;

import com.foreknow.elmboot.mapper.CartMapper;
import com.foreknow.elmboot.mapper.OrderMapper;
import com.foreknow.elmboot.mapper.OrderDetailetMapper;
import com.foreknow.elmboot.po.Cart;
import com.foreknow.elmboot.po.Order;
import com.foreknow.elmboot.service.OrderService;
import com.foreknow.elmboot.po.OrderDetailet;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
@Service
public class  OrderServicelmpl implements OrderService {
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private CartMapper cartMapper;
    @Autowired
    private OrderDetailetMapper OrderDetailetMapper;

    @Override
    public int CreateOrder(Order order){
        orderMapper.CreateOrder(order);          //存入新的订单
        String userId = order.getUserId();         //从订单获取用户编号
        Integer businessId = order.getBusinessId();    // 从订单中获得商家编号
        Integer orderId = order.getOrderId();         // 获得订单编号
        Cart cart = new Cart();
        cart.setUserId(userId);
        cart.setBusinessId(businessId);
        // 根据当前订单中的用户编号和商家编号获得购物车中的信息
        List<Cart> cartList = cartMapper.listCart(cart.getUserId(),cart.getBusinessId());
        for (Cart cart1 : cartList) {
            // 将购物车的信息存入订单详情
            Integer foodId = cart1.getFoodId();
            Integer quantity = cart1.getQuantity();
            OrderDetailet orderDetailet = new OrderDetailet();
            orderDetailet.setOrderId(orderId);
            orderDetailet.setFoodId(foodId);
            orderDetailet.setQuantity(quantity);
            OrderDetailetMapper.CreateOrderDetailet(orderDetailet);
        }
        cartMapper.removeCart(cart.getBusinessId(),cart.getUserId());
        return orderId;
    }
    @Override
    public Order getOrdersById(Integer orderId) {return orderMapper.getOrdersById(orderId);}
    @Override
    public List<Order> listOrderByUserId(String userId) {return orderMapper.listOrderByUserId(userId);}
    @Override
    public int updateOrderByOrderId(Integer orderId){return orderMapper.updateOrderByOrderId(orderId);}
}
